package me.keiwu.pub.util.wx;

import com.alibaba.fastjson.JSONObject;
import jodd.http.HttpResponse;
import me.keiwu.pub.data.wx.WXAccessTokenData;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.pub.util.HttpUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by kei on 06/12/2017.
 */
@Component
public class AccessTokenUtil {


    private static final String ACCESS_TOKEN_API = "https://api.weixin.qq.com/cgi-bin/token";
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);

    @Autowired
    private CacheUtil cacheUtil;

    public String getAccessToken(String appId, String secret) {
        String token = cacheUtil.getWxAccessToken(appId);
        if (StringUtils.isNotBlank(token)) return token;

        logger.info("token not found in redis, get by http, appId={}", appId);
        WXAccessTokenData data = this.doGetAccessToken(appId, secret);
        if (data == null) {
            return null;
        }
        cacheUtil.setWxAccessToken(appId, data.getAccessToken(), data.getExpiresIn());
        return data.getAccessToken();
    }


    private WXAccessTokenData doGetAccessToken(String appId, String secret) {
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", appId);
        params.put("secret", secret);
        try {
            HttpResponse resp = HttpUtil.get(ACCESS_TOKEN_API, params);
            if (resp.statusCode() == HttpStatus.OK.value()) {
                String respBody = resp.body();
                WXAccessTokenData data = JSONObject.parseObject(respBody, WXAccessTokenData.class);
                logger.info("request access_token data: {}", respBody);
                return data;
            }
        } catch (Exception e) {
            logger.error("getAccessToken error: ", e);
        }
        return null;
    }


    public static void main(String[] args) {
        String appId = "wxf1000eb37c6f40e2";
        String secret = "a75c094294ec1fd3e64429eea861227c";
        AccessTokenUtil util = new AccessTokenUtil();
        WXAccessTokenData data = util.doGetAccessToken(appId, secret);
        System.out.println(data);
    }



}
